package user

import (
	cs_message "sanguo/protocol/cs/message"
	"sanguo/node/common/db"
	"encoding/json"
	"github.com/sniperHW/kendynet"
	"sanguo/node/node_game"
	"sanguo/node/common/transaction"
	"time"
	"github.com/golang/protobuf/proto"
)


const (
	register_ok      = 1
	register_timeout = 2
	register_error   = 3
)

type transactionRegister struct {
	transaction.TransactionBase
	user       *User
	errcode     int
}

func (this *transactionRegister) GetModuleName() string {
	return "register"
}

func (this *transactionRegister) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionRegister) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionRegister) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionRegister) Begin() {
	node_game.Infoln(this.user.userID,"register")
	this.user.setStatus(status_register)
	this.user.userData.Name  = this.user.userID
	this.user.userData.Level = 1
	bytes,err := json.Marshal(this.user.userData)
	if nil != err {
		node_game.Infoln(this.user.userID,"login failed7")
		this.errcode = register_error
		this.user.EndTrans(this)		
		return
	}

	go func() {
		//写入到数据库
		key := "user:" + this.user.userID
		ok,err := db.GetRedisClient("game").HSet(key,"userData",string(bytes)).Result()
		if nil != err || !ok {
			node_game.Infoln(this.user.userID,"login failed8")
			this.errcode = register_error
		} else {
			this.errcode = register_ok
		}
		this.user.EndTrans(this)
	}()
}

func (this *transactionRegister) End() {
	if this.errcode == register_ok {
		this.user.loginOK()
	} else {
		onLoginError(this.user,this.user.session,cs_message.EnumType_LOGIN_ERROR)
	}
}

func (this *transactionRegister) Timeout() {
	this.errcode = register_timeout
	this.user.EndTrans(this)
}

func register(user *User,session kendynet.StreamSession) {
	user.transMgr.PushTrans(&transactionRegister{
		user : user,
	},time.Second * 10)	
}
